//
//  MX_DDLogFileManagerWebView.m
//  MXKit
//
//  Created by liyang on 16/6/16.
//  Copyright © 2016年 minxing. All rights reserved.
//

#import "MX_DDLogFileManagerWebView.h"

@implementation MX_DDLogFileManagerWebView

- (NSString *)newLogFileName {
    NSDateFormatter *dateFormatter = [super logFileDateFormatter];
    NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];
    
    return [NSString stringWithFormat:@"webview %@.log", formattedDate];
}

- (BOOL)isLogFile:(NSString *)fileName {
    NSString *webstr = @"webview";
    BOOL hasProperPrefix = [fileName hasPrefix:webstr];
    BOOL hasProperSuffix = [fileName hasSuffix:@".log"];
    BOOL hasProperDate = NO;
    
    if (hasProperPrefix && hasProperSuffix) {
        NSUInteger lengthOfMiddle = fileName.length - webstr.length - @".log".length;
        
        // Date string should have at least 16 characters - " 2013-12-03 17-14"
        if (lengthOfMiddle >= 17) {
            NSRange range = NSMakeRange(webstr.length, lengthOfMiddle);
            
            NSString *middle = [fileName substringWithRange:range];
            NSArray *components = [middle componentsSeparatedByString:@" "];
            
            // When creating logfile if there is existing file with the same name, we append attemp number at the end.
            // Thats why here we can have three or four components. For details see createNewLogFile method.
            //
            // Components:
            //     "", "2013-12-03", "17-14"
            // or
            //     "", "2013-12-03", "17-14", "1"
            if (components.count == 3 || components.count == 4) {
                NSString *dateString = [NSString stringWithFormat:@"%@ %@", components[1], components[2]];
                NSDateFormatter *dateFormatter = [self logFileDateFormatter];
                
                NSDate *date = [dateFormatter dateFromString:dateString];
                
                if (date) {
                    hasProperDate = YES;
                }
            }
        }
    }
    
    return (hasProperPrefix && hasProperDate && hasProperSuffix);
}

@end
